<script setup lang="ts">
import { ref } from 'vue'
import * as accountApi from '@/api/account'
import { message } from 'ant-design-vue'

const calculateDaysUntilExpiration = (expireTime: any) => {
  // 获取当前时间的时间戳
  const now = new Date().getTime()
  // 计算时间差（毫秒）
  const diff = expireTime - now
  // 转换为天数（1天 = 24小时 * 60分钟 * 60秒 * 1000毫秒）
  const days = Math.ceil(diff / (1000 * 60 * 60 * 24)) - 1
  // console.log('days=', days)

  if (Number(days) < 0) {
    return 0
  }
  return days
}

const myModal = ref()

let onlyType = ref<string>('wx')

const showModal = (type = 'wx', id: string) => {
  if (type == 'wx') {
    getWxList()
  } else {
    getXyList()
  }

  console.log('id=', id)
  formState.value.fromRobot = id
  setTimeout(() => {
    handleSelect(id)
  }, 500)

  myModal.value?.showModal()
  onlyType.value = type
}

// 获取闲鱼机器人
const getXyList = async () => {
  try {
    let {
      state,
      data,
      message: msg,
    } = await accountApi.getFishRobotList({
      currentPage: 1,
      pageSize: 100,
    })
    if (state === 200) {
      robotList.value = data.list.map((item: any) => {
        let surplusDay = calculateDaysUntilExpiration(item.expireTime)
        return {
          label: `${item.nickName}（${surplusDay}天可转移）`,
          value: item.id as number,
          hasDay: surplusDay,
          able: true,
        }
      })
      robotListCopy.value = data.list
        .filter((item: any) => formState.value.fromRobot != item.id)
        .map((item: any) => {
          let surplusDay = calculateDaysUntilExpiration(item.expireTime)
          return {
            label: `${item.nickName}（${surplusDay}天到期）`,
            value: item.id as number,
            hasDay: surplusDay,
            able: true,
          }
        })
      // if (robotList.value!.length > 0) {
      //   formState.value.fromRobot = robotList.value![0].value as string
      //   formState.value.toRobot = robotList.value![0].value as string
      // }
      console.log('robotList=', robotList.value)
      console.log('robotListCopy=', robotListCopy.value)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 获取微信机器人
const getWxList = async () => {
  try {
    let {
      state,
      data,
      message: msg,
    } = await accountApi.getList({
      currentPage: 1,
      pageSize: 100,
    })
    if (state === 200) {
      robotList.value = data.list.map((item: any) => {
        let surplusDay = calculateDaysUntilExpiration(item.expireTime)
        return {
          label: `${item.nickName}（${surplusDay}天可转移）`,
          value: item.id as number,
          hasDay: surplusDay,
        }
      })
      // if (robotList.value!.length > 0) {
      //   formState.value.fromRobot = robotList.value![0].value as string
      //   formState.value.toRobot = robotList.value![0].value as string
      // }

      robotListCopy.value = data.list
        .filter((item: any) => formState.value.fromRobot != item.id)
        .map((item: any) => {
          let surplusDay = calculateDaysUntilExpiration(item.expireTime)
          return {
            label: `${item.nickName}（${surplusDay}天到期）`,
            value: item.id as number,
            hasDay: surplusDay,
            able: true,
          }
        })
        console.log('robotListCopy=', robotListCopy.value)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

import type { SelectProps } from 'ant-design-vue'
const robotList = ref<SelectProps['options']>([])
const robotListCopy = ref<SelectProps['options']>([])

// 时长
let dayList = ref<SelectProps['options']>([
  {
    label: '7天',
    value: 7,
    able: true,
  },
  {
    label: '30天',
    value: 30,
    able: true,
  },
  {
    label: '90天',
    value: 90,
    able: true,
  },
])

const emit = defineEmits<{
  refresh: []
}>()

defineExpose({
  showModal,
})

const formRef = ref()
let labelCol = {
  style: {
    // width: '120px',
  },
}
interface FormState {
  fromRobot?: number | string
  toRobot?: number | string
  day?: number | string
}
const formState = ref<FormState>({})

let loading = ref<boolean>(false)

const handleOk = async () => {
  loading.value = true

  const params = {
    channel: 1,
    moveRobotId: formState.value.fromRobot,
    receiveRobotId: formState.value.toRobot,
    moveDayTime: formState.value.day,
  }
  // @ts-ignore
  onlyType.value === 'wx' ? (params.channel = 1) : (params.channel = 3)

  // console.log('params=', params)

  try {
    const { state, message: msg } = await accountApi.robotMoveTime(params)
    if (state === 200) {
      message.success('转移成功')
      handleCancel()
      emit('refresh')
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

const handleCancel = () => {
  myModal.value?.cancelModal()
  formRef.value.resetFields()
}

// select搜索
const filterOption = (input: string, option: any) => {
  return option.label.indexOf(input) >= 0
}

const handleSelect = (selectValue: any) => {
  console.log('selectValue=', selectValue)

  formState.value.day = ''

  // 全部不可选
  dayList.value?.forEach((item: any) => {
    item.able = true
  })

  robotList.value?.forEach(item => {
    if (item.value == selectValue) {
      // console.log('item=', item)
      dayList.value?.forEach((jjtem: any) => {
        // console.log('jjtem=', jjtem)
        if (item.hasDay >= jjtem.value) {
          jjtem.able = false
        }
      })
      // console.log('dayList=', dayList.value)
    }
  })
}
</script>

<template>
  <MyModal ref="myModal" title="转移时长" :top="35">
    <template #content>
      <div style="display: grid; place-items: center">
        <a-form ref="formRef" :model="formState" :label-col="labelCol">
          <a-form-item label="扣除账号" name="fromRobot">
            <a-select
              v-model:value="formState.fromRobot"
              placeholder="请选择"
              allowClear
              style="width: 280px"
              show-search
              :options="robotList"
              :filter-option="filterOption"
              @change="handleSelect"
              :disabled="true"
            >
              <!-- <a-select-option v-for="(item, index) in robotList" :key="index" :value="item.value">
                {{ item.label }}
              </a-select-option> -->
            </a-select>
          </a-form-item>

          <a-form-item label="接收账号" name="toRobot">
            <a-select
              v-model:value="formState.toRobot"
              placeholder="请选择"
              allowClear
              style="width: 280px"
              show-search
              :options="robotListCopy"
              :filter-option="filterOption"
            >
              <!-- <a-select-option v-for="(item, index) in robotListCopy" :key="item" :value="item.value">
                {{ item }}
              </a-select-option> -->
            </a-select>
          </a-form-item>

          <a-form-item label="转移时长" name="day">
            <a-select
              v-model:value="formState.day"
              placeholder="请选择"
              allowClear
              style="width: 280px"
            >
              <a-select-option
                v-for="(item, index) in dayList"
                :key="item"
                :value="item.value"
                :disabled="item.able"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item style="text-align: right">
            <a-space>
              <a-button @click="handleCancel">取消</a-button>
              <a-button type="primary" :loading="loading" @click="handleOk">转移</a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>
    </template>
  </MyModal>
</template>
